//
//  CZNetwork.swift
//  crkWeibo
//
//  Created by 陈荣科 on 15/12/19.
//  Copyright © 2015年 crk. All rights reserved.
//

import AFNetworking

//使用枚举来统一管理错误
enum CZNetworkError: Int{
    case emptyAccessToken = -1 //AccessToken没有值
    case emptyUid = -2      //Uid没有值
    
    //将错误的code和错误的描述关联起来，使用计算型属性,只有get方法
    var errorDescription: String {
    
        get {
        
            //判断不同的类型返回不同的错误信息
            switch self{
            
            case CZNetworkError.emptyAccessToken:
                return "access_token没有值"
            case CZNetworkError.emptyUid:
                return "uid没有值"
            }
        }
    }
    
    //定义一个方法，返回一个错误，根据枚举类型不一样发明会不一样的错误
    func error() -> NSError {
    
        return NSError(domain: "cn.itcast.error.network", code: self.rawValue, userInfo: ["errorDescription" : self.errorDescription])
    }
}

class CZNetworkTool: AFHTTPSessionManager {
    
//    //单例，调用默认构造方法
//      static let sharedInstance:CZNetworkTool = {
//        //baseURLapi前面的内容是一样的
//        //https://api.weibo.com/oauth2/authorize
//
//        let baseURL = NSURL(string: "https://api.weibo.com/")
//        let tool = CZNetworkTool(baseURL: baseURL)
//
//        return tool
//    }()
    
    
     //单例，调用默认构造方法
    static let sharedInstance: CZNetworkTool = CZNetworkTool()
    
    //不让别人访问俄构造方法
    private init (){
    
        //没有初始化的属性
        let baseURL = NSURL(string: "https://api.weibo.com/")
        //在构造函数里面子类不能调用父类的便利构造函数，需要调用父类的之地ing构造函数
        super.init(baseURL: baseURL, sessionConfiguration: nil)
        
        //方法的调用必须在super.init只有调用父类的super.init之后，对象才嫩创建完毕，
//        对象创建完毕才能调用队形的方法
        
        //设置响应的序列化器，支持text/plain
        self.responseSerializer.acceptableContentTypes?.insert("text/plain"
)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 授权相关
    //appkey
    private let client_id = "1255432106"
    
    //app秘钥
    private let client_secret = "1ef31d3cd1dd35d5e69f4b8714c137fa"
    
    let redirect_uri = "http://www.baidu.com/"
    
    ///拼接登录界面的URL地址
    func oAuthURL() -> NSURL {
    
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        
        return NSURL(string:urlString)!
    }
    //MARK: - 加载AccessToken
    func loadAccessToken(code:String,finished:(result:[String: AnyObject]?,error: NSError?) ->()){
    
        //url地址
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        //请求参数,字典
        let parameters = [
        
            "client_id":client_id,
            "client_secret":client_secret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirect_uri
        ]
        
        //发送post请求
        POST(urlString, parameters: parameters, success: { (_, result) -> Void in
            
            let dict = result as? [String: AnyObject]
            
            finished(result: dict, error: nil)
            
            }) { (_, error) -> Void in
               finished(result:nil, error: error)
        }
    }
    
    //加载用户信息
    func loadUerInfo(finished:(result: [String: AnyObject]?,error: NSError?) ->()) {
    
        
        //判断access_token是否有值
        //TODO: 测试accesstoken没有值
//        CZUserAccount.loadUserAccount()?.access_token = nil
        
        guard let access_token = CZUserAccount.loadUserAccount()?.access_token else{
        
            //自定义错误提示
            let error = CZNetworkError.emptyAccessToken.error()
//            print("access_token没有值")
            
            //告诉调用者，网络请求出错
            finished(result: nil, error: error)
            return
        }
        //外面也可以用access_token
        
        //测试uid没有值
//        CZUserAccount.loadUserAccount()?.uid = nil
        //判断uid是否有值
        guard let uid = CZUserAccount.loadUserAccount()?.uid else {
            let error = CZNetworkError.emptyUid.error()
            
            finished(result: nil, error: error)
         return
        }
        
        //url地址,https://api.weibo.com/2/users/show.json可以省略baseUrl，AFN会帮我们加上
        let userURL = "2/users/show.json"
        
        //请求参数
        let parameters = [
            
            "access_token":access_token ,
            "uid":uid
        ]
        
        GET(userURL, parameters: parameters, success: { (_, result) -> Void in
            
            let dict = result as? [String: AnyObject]
            
            finished(result:dict, error: nil)
            
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
        }
    }
    
    //MARK: - 获取微博数据
    func loadStatus(since_id: Int, max_id: Int, finished: (result:[String: AnyObject]?,error: NSError?) -> ()) {
    
        //判断access_token
        guard let access_token = CZUserAccount.userAccount?.access_token else{
        
            let error = CZNetworkError.emptyAccessToken.error()
            
            finished(result: nil, error: error)
            return
        }
        
        //url https://api.weibo.com/2/statuses/home_timeline.json
        let statusURL = "2/statuses/home_timeline.json"
        
        var parameters:[String:AnyObject] = ["access_token": access_token]
        
        if since_id > 0 {
            //表示别人传了since_id，下拉刷新微博数据
            parameters["since_id"] = since_id
        }else if max_id > 0 {
            //表示别人传了max_id，上啦加载微博数据
            parameters["max_id"] = max_id - 1
        }
        
        //判断是否加载本地数据还是网络数据
        
        let debug = false
        
        
        if debug{
            //加载本地数据
            loadLocalStatus(finished)
            
        }else{
            
            GET(statusURL, parameters: parameters, success: { (_, result) -> Void in
                
                let dict = result as? [String: AnyObject]
                finished(result: dict, error: nil)
                
                }) { (_, error) -> Void in
                    finished(result: nil, error: error)
            }
            
        }
    }
    
    ///本地加载数据
    func loadLocalStatus(finished:(result: [String: AnyObject]?,error: NSError?) ->()) {
    
        //1、获取statuses.json路径
        let path = NSBundle.mainBundle().pathForResource("statuses.json", ofType: nil)!
        
        //2.加载到内存中（NSData）
        let data = NSData(contentsOfFile: path)!
        
        //3、转成json
//        do {
//            
//            let json = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0))
//            
//            let dict = json as? [String: AnyObject]
//            
//            finished(result: dict, error: nil)
//        }catch {
//        
//            print("json转换异常")
//            let error = NSError(domain: "cn.itcast.error.loadlocaleStatus", code: -3, userInfo: ["errorDescription" : "加载本地数据错误"])
//            finished(result: nil, error: error)
//        
//        }
        
        //强制try,和强制拆包一样，如果出现错误，程序就会立即停止运行
        let json = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0))
        let dict = json as? [String: AnyObject]
        
        finished(result: dict, error: nil)
    }
    
}
